package cn.codingjc.aurora.module.system.biz.api.oauth;

import cn.codingjc.aurora.module.system.biz.api.oauth.Oauth2Api;
import cn.codingjc.aurora.module.system.biz.core.MyRequest;
import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Lists;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.config.AuthSource;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @ClassName Oauth2ApiImpl
 * @Description Oauth2 相关
 * @Author jccoding
 * @Date 2024/2/25 12:53
 * @Version 1.0
 **/
@Slf4j
public class Oauth2ApiImpl implements Oauth2Api {
    @Override
    public String login(HttpServletResponse httpServletResponse) {
        AuthRequest request = getRequest();
        String authorizeUrl = request.authorize(AuthStateUtils.createState());
        return authorizeUrl;
    }

    @Override
    public String callback(String code, AuthCallback callback) {
        log.info("callback params: code:{}, callback:{}", code, JSON.toJSONString(callback));
        AuthRequest request = getRequest();
        callback.setCode(code);
        AuthResponse authResponse = request.login(callback);
        if (!authResponse.ok()) {
            return "Login error";
        }
        if (authResponse.getCode() == 200) {
            return JSON.toJSONString(authResponse.getData());
        }
        return null;
    }

    @Override
    public String redirectToOAuthLogin() {
        return "redirect:/oauth2/authorization/github";
    }

    @Override
    public String hello() {
        return "hello";
    }

    private AuthRequest getRequest() {
        AuthConfig authConfig = AuthConfig.builder()
                .clientId("")
                .clientSecret("")
                .redirectUri("")
                .scopes(Lists.newArrayList())
                .build();
        return new MyRequest(authConfig, new AuthSource() {
            @Override
            public String authorize() {
                return null;
            }

            @Override
            public String accessToken() {
                return null;
            }

            @Override
            public String userInfo() {
                return null;
            }
        });
    }
}
